import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';

const Dashboard = ({ user, onLogout }) => {
  const [teams, setTeams] = useState([]);
  const [selectedTeam, setSelectedTeam] = useState(null);
  const [documents, setDocuments] = useState([]);
  const [newTeamName, setNewTeamName] = useState('');
  const [newTeamDesc, setNewTeamDesc] = useState('');
  const [newDocTitle, setNewDocTitle] = useState('');
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadTeams();
  }, [user]);

  const loadTeams = async () => {
    try {
      const response = await axios.get(`/api/teams/user/${user.id}`);
      setTeams(response.data);
      if (response.data.length > 0) {
        setSelectedTeam(response.data[0]);
        loadDocuments(response.data[0].id);
      }
    } catch (error) {
      console.error('加载团队失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const loadDocuments = async (teamId) => {
    try {
      const response = await axios.get(`/api/documents/team/${teamId}`);
      setDocuments(response.data);
    } catch (error) {
      console.error('加载文档失败:', error);
    }
  };

  const createTeam = async (e) => {
    e.preventDefault();
    try {
      await axios.post('/api/teams', {
        name: newTeamName,
        description: newTeamDesc
      }, { params: { userId: user.id } });
      
      setNewTeamName('');
      setNewTeamDesc('');
      loadTeams();
    } catch (error) {
      console.error('创建团队失败:', error);
    }
  };

  const createDocument = async (e) => {
    e.preventDefault();
    if (!selectedTeam) return;
    
    try {
      await axios.post('/api/documents', {
        title: newDocTitle,
        content: '',
        teamId: selectedTeam.id
      }, { params: { userId: user.id } });
      
      setNewDocTitle('');
      loadDocuments(selectedTeam.id);
    } catch (error) {
      console.error('创建文档失败:', error);
    }
  };

  if (loading) {
    return <div className="container">加载中...</div>;
  }

  return (
    <div>
      <header className="header">
        <div className="header-content">
          <h1>协同文档系统</h1>
          <div className="user-info">
            <span>欢迎, {user.username}</span>
            <button className="btn btn-secondary" onClick={onLogout}>
              退出登录
            </button>
          </div>
        </div>
      </header>

      <div className="layout">
        <aside className="sidebar">
          <h3>我的团队</h3>
          <form onSubmit={createTeam}>
            <div className="form-group">
              <input
                type="text"
                placeholder="新团队名称"
                value={newTeamName}
                onChange={(e) => setNewTeamName(e.target.value)}
                required
              />
            </div>
            <div className="form-group">
              <input
                type="text"
                placeholder="团队描述"
                value={newTeamDesc}
                onChange={(e) => setNewTeamDesc(e.target.value)}
              />
            </div>
            <button type="submit" className="btn btn-primary">
              创建团队
            </button>
          </form>

          <div style={{ marginTop: '20px' }}>
            {teams.map(team => (
              <div
                key={team.id}
                className={`document-item ${selectedTeam?.id === team.id ? 'active' : ''}`}
                onClick={() => {
                  setSelectedTeam(team);
                  loadDocuments(team.id);
                }}
              >
                <strong>{team.name}</strong>
                <p style={{ margin: 0, fontSize: '12px', color: '#666' }}>
                  {team.description}
                </p>
              </div>
            ))}
          </div>
        </aside>

        <main className="main-content">
          {selectedTeam ? (
            <div>
              <h2>{selectedTeam.name} - 文档列表</h2>
              
              <form onSubmit={createDocument}>
                <div className="form-group">
                  <input
                    type="text"
                    placeholder="新文档标题"
                    value={newDocTitle}
                    onChange={(e) => setNewDocTitle(e.target.value)}
                    required
                  />
                </div>
                <button type="submit" className="btn btn-primary">
                  创建文档
                </button>
              </form>

              <div style={{ marginTop: '20px' }}>
                {documents.map(doc => (
                  <div key={doc.id} className="card">
                    <h3>
                      <Link to={`/document/${doc.id}`}>{doc.title}</Link>
                    </h3>
                    <p>创建时间: {new Date(doc.createdAt).toLocaleString()}</p>
                    <p>最后修改: {new Date(doc.updatedAt).toLocaleString()}</p>
                  </div>
                ))}
              </div>
            </div>
          ) : (
            <div className="card">
              <h3>请先创建或加入一个团队</h3>
            </div>
          )}
        </main>
      </div>
    </div>
  );
};

export default Dashboard;